import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ChatChannel implements Runnable{
    Socket socket;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    String name;
    static Map<String,ObjectOutputStream> allMap= new HashMap<String,ObjectOutputStream>();

    public ChatChannel(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            recvNameAndEcho();
        while (true){
//        oos.writeObject(name+"说:"+ois.readObject());
            String msg=(String) ois.readObject();
            sendToAll(name + "说：" + msg);
        }

        }
        catch(IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void sendToAll(String name) throws IOException {
        for (ObjectOutputStream os : allMap.values()) {
            os.writeObject(name);
            os.flush();
        }
    }

    private void recvNameAndEcho() throws IOException, ClassNotFoundException {
        InputStream is = socket.getInputStream();
        ois = new ObjectInputStream(is);
        name = (String) ois.readObject();
        System.out.println(name + "进入聊天室");
        sendToAll("系统提示"+name + "进入聊天室");
        OutputStream os = socket.getOutputStream();
        oos = new ObjectOutputStream(os);
        allMap.put(name, oos);
        oos.writeObject(name + ",您好！欢迎您进入聊天室");
        oos.flush();
    }
}
